//
//  ABPormptView.m
//  ZYTS-iPhone
//
//  Created by yuzhou on 13-3-18.
//  Copyright (c) 2013年 wzyk. All rights reserved.
//

#define dismissOtherPrompt @"dismissOtherPrompt"

#import "ABPromptView.h"
#import <QuartzCore/QuartzCore.h>

@implementation ABPromptView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

- (id)initWithTitle:(NSString *)title
{
    UIFont *font = [UIFont systemFontOfSize:16];
    CGSize size = [title sizeWithFont:font constrainedToSize:CGSizeMake(200, 999) lineBreakMode:NSLineBreakByCharWrapping];
    size.width = MIN(size.width, 200);
    self = [super initWithFrame:CGRectMake(0, 0, size.width+10, size.height+10)];
    if (self) {
        self.backgroundColor = [UIColor blackColor];
        self.layer.shadowColor = [UIColor blackColor].CGColor;
        self.layer.shadowOpacity = 0.45;
        self.layer.shadowOffset = CGSizeMake(0, 0);
        self.layer.masksToBounds = NO;
        self.layer.shadowPath = [UIBezierPath bezierPathWithRect:self.bounds].CGPath;
        
        UILabel *titleLabel = [[[UILabel alloc] initWithFrame:CGRectMake(5, 5, size.width, size.height)] autorelease];
        titleLabel.text = title;
        titleLabel.numberOfLines = 0;
        titleLabel.textAlignment =NSTextAlignmentCenter;
        titleLabel.font = font;
        titleLabel.textColor = [UIColor whiteColor];
        titleLabel.backgroundColor = [UIColor clearColor];
        [self addSubview:titleLabel];
    }
    return self;
}

- (void)show
{
    [[NSNotificationCenter defaultCenter] postNotificationName:dismissOtherPrompt object:nil];
    UIWindow *window = [[UIApplication sharedApplication] keyWindow];
    self.center = CGPointMake(window.frame.size.width*0.5, window.frame.size.height*0.75);
    [window addSubview:self];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dismiss) name:dismissOtherPrompt object:nil];
    [self performSelector:@selector(dismiss) withObject:nil afterDelay:1];
}

- (void)dismiss
{
    [NSObject cancelPreviousPerformRequestsWithTarget:self];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [UIView animateWithDuration:0.5 animations:^{
        CGRect rect = self.frame;
        rect.origin.y -= 50;
        self.frame = rect;
        self.alpha = 0;
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
    
//    [CATransaction begin];
//    [CATransaction setValue:[NSNumber numberWithDouble:0.5] forKey:kCATransactionAnimationDuration];
//    self.layer.transform = CATransform3DMakeTranslation(0, 0.1, -0.1);
//    [CATransaction setCompletionBlock:^{
//        [self removeFromSuperview];
//    }];
//    [CATransaction commit];
}

@end
